package com.dubbo.lian.cms.modules.app.mq;
 import org.apache.activemq.command.ActiveMQObjectMessage;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.stereotype.Component;
 import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
 /**
 * 消息转换器
 *
 * 日期：2015年9月28日 下午12:17:11
 */
@Component("activeMQMessageConverter")
public class ActiveMQMessageConverter implements MessageConverter {
     public Message toMessage(Object obj, Session session) throws JMSException {
        if (obj instanceof PersonInfo) {
            ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
            msg.setObject((PersonInfo) obj);
            return msg;
        } else if(obj instanceof Email){
            ActiveMQObjectMessage msg = (ActiveMQObjectMessage) session.createObjectMessage();
            msg.setObject((Email) obj);
            return msg;
        }else {
            System.out.println("Object:[" + obj + "] is not a instance of PersonInfo.");
            throw new JMSException("Object:[" + obj + "] is not a instance of PersonInfo.");
        }
    }
     public Object fromMessage(Message message) throws JMSException {
        System.out.println();
        System.out.println("执行ActiveMQMessageConverter消息转换器 ,message信息如下: " + message.toString());
        if (message instanceof ObjectMessage) {
            ObjectMessage oMsg = (ObjectMessage) message;
            if (oMsg instanceof ActiveMQObjectMessage) {
                ActiveMQObjectMessage aMsg = (ActiveMQObjectMessage) oMsg;
                try {
                    PersonInfo personInfo = (PersonInfo) aMsg.getObject();
                    personInfo.setUserName(personInfo.getUserName() + "，这是二次加工后的用户名.");
                     System.out.println("对实体bean进行二次加工后的结果:" + personInfo.toString());
                     return personInfo;
                } catch (Exception e) {
                    System.out.println("Message:[" + message + "] is not a instance of personInfo.");
                    throw new JMSException("Message:[" + message + "] is not a instance of personInfo.");
                }
            } else {
                System.out.println("Message:[" + message + "] is not " + "a instance of ActiveMQObjectMessage[personInfo].");
                throw new JMSException("Message:[" + message + "] is not " + "a instance of ActiveMQObjectMessage[personInfo].");
            }
        } else {
            System.out.println("Message:[" + message + "] is not a instance of ObjectMessage.");
            throw new JMSException("Message:[" + message + "] is not a instance of ObjectMessage.");
        }
    }
 }
